<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, Rule, useForm } from '/@/components/Form';

import { tableFormSchema } from './data';
import { add, update } from '/@/api/project/planDetail';

export default defineComponent({
  name: 'formModal',
  components: { BasicModal, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);

    const [registerForm, { resetFields, updateSchema, setFieldsValue, validate }] = useForm({
      labelWidth: 100,
      schemas: tableFormSchema,
      showActionButtonGroup: false,
    });

    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      await resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      let formData = data.record;

      if (unref(isUpdate)) {
        setFieldsValue({
          ...formData,
        });
      }else{
        setFieldsValue({
          planId: data.planId,
        });
      }
    });

    const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '修改'));

    async function handleSubmit() {
      try {
        setModalProps({ confirmLoading: true });
        const values = await validate();

        if (unref(isUpdate)) {
          update(values)
        } else {
          add(values)
        }

        closeModal();
        emit('success');
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    return { registerModal, registerForm, getTitle, handleSubmit };
  },
});
</script>
